const hostconfig = require("@/utils/config.js")
const urlConfig = require("@/utils/request/urlconfig.js")
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
import moment from "moment";
const momentTime = (time,format)=>{
  let backTime = ''
  //1. 将moment转换为时间戳
  let _t = moment(time).valueOf();
  // 2. 将时间戳转换为时间
  backTime = moment(_t).format(format);
  return backTime;
}
//加密
const encrypt = (p) => {
  let pubKey = "-----BEGIN PUBLIC KEY-----\n" +
      "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAiKO/Gxms8Xmn4TAZU2JEViSlVAz2zUaV8x2ixkqvmo33sYTHMY59KsEl1MiPZxd/z0+VUyhLD+FuxyBwoVEVo7tEb+Fw9wZA7BOInfFLnfNVyTWQUd/xQeTBb2hj4HYQkwKyGpyyJgorFb79rWm6FF8/bl1hfJ1DAZvOSIvyC+k/0flqxLaeVvnu4nikc2tiaeZuk7SX2m2JqHCQXn225o4NAngga34aF/7EK4cZXUeFu4BgrbNc+NP4k6cXAM8gsoOq1xhKlYJa9EOyDPY50KN691PwhEwlkSfnOXfIiNTBL5GZV8rugR6BA13VKrjrm8YDgZuuR5XeisMMsZq+8ako6FtRrFg9LwRiYv2sSaLUn3CkP58uuAE/PPFSyKoaol3b8C7QqAtNN5bEpoOGYc3z6kDQygUcVjSSNOz9tsM167MKpY/TMSq5bdX6+k4mV6zlyUGgsrcaCQ2KaSFE037PGivcXvo/s6HqzzbLNJHKsBHrw4Kx7VVsTbWgtvZYuhEWEw1sE98cCKKVJVZPbB5G/eoy+wvZkWP+oCKEZuuMWdI40a+ndlTTWPcOrEpKe/5FSe2PSrWY9R52KVpxgW6G53k8I4IWMyzuaEINn5Ft1V5C0BZPey0hRnSChgxirHZGeiP8931ZuaM/3QLp3ieaNb0omSTbvfWGJIorsVsCAwEAAQ==\n" +
      "-----END PUBLIC KEY-----"
  let ras = new JSEncrypt()
  ras.setPublicKey(pubKey);
  let np = ras.encrypt(p)
  return np;
}
// host[i] 提取、替换 
// 将[host1] [host2] 等替换成相应的 host 地址
// @param
// url urlConfig中对应的api
// config	域名地址列表
const changeHost = (url, config) => {
	// 匹配 url 中有无 [文字] 格式的字符，
	// 有：取返回的数组中的第一项
	// 无：取 ""
	var _host = url.match(/\[(\S*)\]/) ? url.match(/\[(\S*)\]/)[0] : ""
	var api = url.replace(_host, "")
	var _url = ''

	switch (_host) {
		case '[host1]':
			_url = config.host1 + api
			break;
		case '[host2]':
			_url = config.host2 + api
			break;
		default:
			_url = url
			break;
	}
	return _url
}


// Storage封装 (同步/异步)
const mystorage = {
	// 同步获取storage信息
	getStorage: (key, needWait) => {
		needWait = needWait || false
		let strVal = ""
		if (needWait) {
			// 异步获取
			try {
				return new Promise((res, rej) => {
					strVal = uni.getStorageSync(key)
					res(strVal)
				})
			} catch (e) {}
		} else {
			// 同步获取
			try {
				strVal = uni.getStorageSync(key);
			} catch (e) {}
		}
		return strVal
	},
	// 同步设置storage信息
	setStorage: (key, val, needAwait) => {
		needAwait = needAwait || false
		if (key && val) {
			if (needAwait) {
				return new Promise((res, rej) => {
					uni.setStorage({
						key: key,
						data: val,
						success: function (e) {
							res(key)
						}
					})
				})
			} else {
				uni.setStorageSync(key, val)
			}
		}
	},
	// 同步清除storage信息
	removeStorage: (key) => {
		uni.removeStorageSync(key)
	},
	// 同步清除全部storage信息
	clearStorage: () => {
		uni.clearStorageSync()
	}
}

// api地址处理 封装请求
const request = ({
	url = '',
	params = '',
	method = 'GET',
	header = {},
	sussfn = function () {},
	failfn = function () {}
}) => {
	// 整理地址格式
	if (urlConfig[url]) {
		var _hostUrl = changeHost(urlConfig[url], hostconfig)
	} else {
		uni.showToast({
			title: '请先配置正确的api地址！！',
			duration: 1500,
			icon: 'none'
		});
		return
	}
	header = header.toString() == "{}" ? {
		'content-type': 'application/json'
	} : header
	uni.request({
		url: _hostUrl,
		data: params,
		header: header,
		method: method,
		success: function (res) {
			sussfn(res.data)
		},
		fail: function (err) {
			failfn(err)
		}
	})
}

// 获取地址栏信息
const getParmas = (name) => {
	let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
	let r = window.location.search.substr(1).match(reg)
	if (r !== null) {
		return unescape(r[2])
		return null
	}
}
/**
 * 获取微信扫码进入url参数
 * @param {*} url 小程序解析出来的url地址
 * @param {*} name 想要获取的参数
 */
const getQueryString = (url, name) => {
	var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i');
	var r = url.substr(1).match(reg);
	if (r != null) {
		// console.log("r = " + r);
		// console.log("r[2] = " + r[2]);
		return r[2]
	}
	return null;
}

//路由跳转
/**
 * @param {*} name // 跳转名称
 * @param {*} url  // 跳转地址
 * 
 * uni.navigateTo(OBJECT) 保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面。
 * uni.redirectTo(OBJECT)  关闭当前页面，跳转到应用内的某个页面。
 * uni.reLaunch(OBJECT) 关闭所有页面，打开到应用内的某个页面。
 * uni.switchTab(OBJECT) 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
 * uni.navigateBack(OBJECT) 关闭当前页面，
 * 返回上一页面或多级页面。可通过getCurrentPages() 获取当前的页面栈，决定需要返回几层。
 * uni.preloadPage(OBJECT) 预加载页面，是一种性能优化技术。被预载的页面，在打开时速度更快。
 */
const navFn = (name, url) => {
	name = name || 'to'
	url = url || '/pages/index/index'
	let key = name
	switch (key) {
		case 'to'://保留当前页面，跳转到应用内的某个页面
			uni.navigateTo({
				url: url
			})
			break;
		case 'too'://关闭所有页面，打开到应用内的某个页面。
			uni.reLaunch({
				url: url
			})
			break;
		case 'rto'://关闭当前页面，跳转到应用内的某个页面。
			uni.redirectTo({
				url: url
			})
			break;
		case 'back':
			uni.navigateBack({
				delta: 2
			})
			break;
		case 'sto'://跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
			uni.switchTab({
				url: url
			})
			break;
		default:
			uni.navigateTo({
				url: url
			})
			break;
	}
}

// 获取微信openid
const getWxLogin = (that, app) => {
	// 获取用户code
	uni.login({
		// #ifdef MP-WEIXIN
		provider: 'weixin',
		// #endif
		success(res) {
			let _code = {
				code: res.code,
			}
			// console.log(res, "code")
			//使用code 换取openid 和 unionid
			uni.$_httpPost({
				url: "get-openid",
				that: that,
				params: _code,
				success(op) {
					// console.log(op, '获取openid')
					let _op = op.data
					app.openid = _op.openid
					app.unionid = _op.unionid || ''
				},
				fail(err) {
					console.log(err);
				}
			})
		}
	})
}
/**
 * @param {*} code //小程序code
 * @param {*} that 页面this
 * @param {*} url 地址
 * @param {*} app 全局参数
 * @param {*} needCallback 是否需要回调方法
 * @returns 
 */
// 使用 code（获取号码code） + openid+unionid 登录
const loginWxMpPhone = (code, that, url, app, needCallback = function () {}) => {

	url = url || ""
	let _data = {
		inviteCode: app.soucreCode,
		unionid: app.unionid || null,
		openid: app.openid,
		source: app.source,
		code: code || '',
		screenId: app.screenId || ''
	}
	uni.showLoading({
		title: '登录中……',
		mask: false
	})
	uni.$_httpPost({
		url: "loginwxmpphone",
		that: that,
		params: _data,
		success(mp) {
			uni.$_setToken({
				token: mp.data.token,
			})
			// console.log(mp, '登录成功');
			app.isLogin = true
			that.isLogin = app.isLogin
			uni.$_getSubscribeList(that)

			let tmirs = setTimeout(() => {
				needCallback(true)
				clearTimeout(tmirs)
			}, 400);
			uni.hideLoading()

		},
		fail(err) {
			console.log(err);
			uni.$_timeOut(that, err.message)
		}
	})

}

const publicModal = (text, trueModal = function () {},falseModal = function () {},confirmText) => {
	uni.showModal({
		title: "提示",
		content: text,
		confirmText:confirmText,
		success: function (res) {
			if (res.confirm) {
				trueModal()
				// console.log("确定")
			}else{
				falseModal()
			}
		},
	});
}

// 获取消息订阅模板
const getSubscribe = () => {
	let subscribe = []
	try {
		subscribe = uni.getStorageSync('subscribeTemplate');
	} catch (e) {}
	return subscribe
}
//获取是否开启订阅
const getIsSubscribe = () => {
	let isSubscribe = []
	try {
		isSubscribe = uni.getStorageSync('isSubscribe');
	} catch (e) {}
	return isSubscribe
}
//获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限
const getUserSetting = () => {
	uni.getSetting({
		withSubscriptions: true,
		success(res) {
			uni.setStorageSync('isSubscribe', res.subscriptionsSetting.mainSwitch)
		},
	});

}
//消息订阅模板存入本地
const getSubscribeList = (that) => {
	uni.$_get({
		url: "get-msg-tpl",
		that: that,
		needlogin: true,
		success: (res) => {
			// console.log(res.data,"模板消息");	
			let template = res.data;
			uni.$_setStorage('subscribeTemplate', template)

			// uni.setStorageSync('subscribeTemplate',template)

		},
		fail: (err) => {
			that.$u.toast(err.message);
		},
	});
}



//微信消息订阅
const newsSubscription = (tmplId, isSubscribe, subscribeFn = function () {}) => {
	// if (!isSubscribe) {
	// 	uni.$_publicModal("您还未开启微信消息订阅，是否前往开启？", function () {
	// 		uni.openSetting();
	// 	});
	// } else {
	// 	// console.log(tmplId,'接收的id');

	// }
	let isArray = Array.isArray(tmplId)
	// console.log(isArray,'接收的id是否为数组');
	uni.requestSubscribeMessage({
		tmplIds: isArray ? tmplId : [tmplId],
		success(res) {
			// if (res[tmplId] === "accept") {
			//   // console.log(res,'用户主动点击同意');
			// } else if (res[tmplId] === "reject") {
			//   // console.log(res,'用户主动点击拒绝');
			// } else {
			//   wx.showToast({
			//     title: "授权订阅消息有误",
			//     icon: "none",
			//   });
			// }
			// console.log(res,'消息订阅');
			subscribeFn()
		},
		fail(err) {
			console.log(err);
			subscribeFn()
		},
	});
}

// 动态修改标题
const changeTitle = (title) => {
	title = title || ""
	uni.setNavigationBarTitle({
		title: title,
	});
}

// 获取当前时间
const getNowDate = (moth) => {
	// moth-year、month、day
	let date = new Date(),
		year = date.getFullYear(), //获取完整的年份(4位)
		month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
		strDate = date.getDate() // 获取当前日(1-31)
	if (month >= 1 && month <= 9) month = '0' + month // 如果月份是个位数，在前面补0
	if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate // 如果日是个位数，在前面补0

	let currentdate = ``
	// ${year} - ${month} - ${strDate}
	switch (moth) {
		case 'year':
			currentdate = `${year}`
			break;
		case 'month':
			currentdate = `${year}-${month}`
			break;
		case 'day':
			currentdate = `${year}-${month}-${strDate}`
			break;
		default:
			break;
	}
	return currentdate
}

// 定时器封装
const timeOut = (that, title, time) => {
	time = time || 500
	title = title || ''
	if (title != '') {
		let timer = setTimeout(() => {
			that.$u.toast(title, 2000)
			clearTimeout(timer)
		}, time)
	}
}

//位置信息
const locationFn = (app, agreeBack = function () {}, refuseBack = function () {}) => {
	uni.authorize({
		scope: 'scope.userLocation',
		success() {
			//获取当前位置
			uni.getLocation({
				type: 'wgs84',
				success: function (res) {
					console.log('当前位置的信息：' + res);
					console.log('当前位置的经度：' + res.longitude);
					console.log('当前位置的纬度：' + res.latitude);
					let location = {
						log: res.longitude,
						lat: res.latitude
					}
					location = JSON.parse(JSON.stringify(location))
					// let log = res.longitude
					// let lat = res.latitude
					// console.log('经纬度：' ,location);
					app.location = location
					// console.log('经纬度：' ,app.location);
					agreeBack()
				}
			});

		},
		fail() {
			refuseBack()
		}
	})
}

//判断浏览器是否是微信浏览器
const checkIsWechatBrowser = () => {
  return (
    navigator.userAgent.toLowerCase().match(/MicroMessenger/i) ==
    "micromessenger"
  );
};

//微信浏览器中打开H5隐藏顶部导航方法
const hidePageNavInWechatBrowser = () => {
	// console.log(123)
  //#ifdef H5
  if (checkIsWechatBrowser()) {
	  
    let pageNav = document.getElementsByTagName("uni-page-head");
    if (pageNav && pageNav[0]) {
      pageNav[0].style.display = "none";
    }
  }
  //#endif
};
const isWeixin = () =>{
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
	return true;
  } else {
	return false;
  }
};

// 16进制转10进制整数
const hex2int =(hex) =>{
	var len = hex.length,
		a = new Array(len),
		code;
	for (var i = 0; i < len; i++) {
		code = hex.charCodeAt(i);
		if (48 <= code && code < 58) {
			code -= 48;
		} else {
			code = (code & 0xdf) - 65 + 10;
		}
		a[i] = code;
	}
		
	return a.reduce(function(acc, c) {
		acc = 16 * acc + c;
		return acc;
	}, 0);
}
// 16进制转buffer
const hexStringToArrayBuffer = (str) =>{
	if (!str) {
		return new ArrayBuffer(0);
	}
	var buffer = new ArrayBuffer(str.length);
	let dataView = new DataView(buffer)
	let ind = 0;
	for (var i = 0, len = str.length; i < len; i += 2) {
		let code = parseInt(str.substr(i, 2), 16)
		dataView.setUint8(ind, code)
		ind++
	}
	return buffer;
}

const getCrc_16_ibm = (cData_str) =>{
	  let arr = [];
	  let len = cData_str.length / 2
	  for (let i = 0; i < len; i++) {
		let a = '0x' + cData_str.slice(i * 2, i * 2 + 2);
		arr.push(a);
	  }
	  let crc = CRC16_IBM(arr);
	  let crcLen = crc.length;
	  crc = crcLen >= 4 ? crc.slice(2, 4) + crc.slice(0, 2) : crcLen == 3 ? crc.slice(1, 3) + '0' + crc.slice(0, 1) : crcLen == 2 ? crc + '00' : '0' + crc + '00';
	  return crc;
}
const CRC16_IBM = (cData) =>{
  let cLen = cData.length;
  let CRC16Table = [
	0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
	0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
	0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
	0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
	0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
	0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
	0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
	0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
	0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
	0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
	0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
	0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
	0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
	0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
	0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
	0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
	0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
	0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
	0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
	0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
	0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
	0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
	0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
	0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
	0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
	0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
	0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
	0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
	0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
	0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
	0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
	0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
  ];

  var result = 0;
  var tableNo = 0;

  for (let i = 0; i < cLen; i++) {
	tableNo = ((result & 0xff) ^ (cData[i] & 0xff));
	result = ((result >> 8) & 0xff) ^ CRC16Table[tableNo];
  }
  return result.toString(16).toUpperCase();
}

//得到16进制数据
const ab2hex = (buffer) =>{
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('')
}

/**
 * @param {*} ids //蓝牙所需要的id
 * @param {*} buff 下发的指令/ArrayBuffer类型
 * @returns 
 */
//蓝牙系统配对
//拆分返回的数据成新的数组
const parse_blue_response = (str,chunkSize) =>{
	const regex = new RegExp('.{1,' + chunkSize + '}', 'g');
	let arr = Array.from(str.match(regex) || [])
	let dataList = []
	dataList = arr.slice(4,-2)
	let obj = {
		Head:arr[0],
		Cmd:arr[1],
		Data_len:arr[2]+ arr[3],
		Data:dataList,
		Check_Crc:arr.slice(-2),
	}
	  return obj;
}
//拆分返回的数据成新的数组
const parseStrtoArr = (str,chunkSize) =>{
	const regex = new RegExp('.{1,' + chunkSize + '}', 'g');
	let arr = Array.from(str.match(regex) || [])
	
	  return arr;
}
const connectBluetooth = (that,ids,buff) =>{
	uni.writeBLECharacteristicValue({
		// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
		deviceId: ids.deviceId,
		// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
		serviceId: ids.serviceId,
		// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
		characteristicId: ids.writeId, //第二步写入的特征值
		// 这里的value是ArrayBuffer类型
		value: buff,
		success: function(res) {
			//此时设备已接收到你写入的数据
			console.log("写入成功", res)
			uni.$_startNotice(that,ids)
		},
		fail: function(err) {
			console.log(err)
			
		},
		// complete: function() {
		// 	console.log("调用结束");
	
		// }
	})
}

const startNotice = (that,ids) =>{
	
	uni.notifyBLECharacteristicValueChange({
		state: true, // 启用 notify 功能
		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
		deviceId: ids.deviceId,
		// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
		serviceId: ids.serviceId,
		// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
		characteristicId: ids.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
		success(res) {
			//接收蓝牙返回消息
			// that.listenValueChange()
			uni.onBLECharacteristicValueChange(result => {
				// console.log("监听低功耗蓝牙设备的特征值变化", result);
				if (result.value) {
					let resHex = ab2hex(result.value)
					console.log('设备返回原始数据', resHex)
					dataObj = parse_blue_response(resHex, 2)
					console.log('新数据', dataObj)
					that.bluedata = dataObj
					console.log(that.bluedata,'data')
				}
			})
	
		},
		fail(err) {
			
		}
	})
	
}
//处理16进制，补位0为length位
const padHexString = (hexStr,length) =>{
  let paddedHex = Number(`0x${hexStr}`).toString(16).padStart(length, '0');
  return paddedHex;
}
//防抖
const debounce = (fn, wait)=> {
    let timeout = null;
    wait = wait || 600;
    return function () {
      let that = this;
      if(timeout !== null)   clearTimeout(timeout);
      timeout = setTimeout(() => {
        fn.apply(that);
      }, wait);
    }
}
const getWeekDataList = (data) =>{
	//根据日期获取本周周一~周日的年-月-日
	var weekList = [];
	var date = new Date(data);
	//判断本日期是否为周日，获取本周一日期
	if(date.getDay()=="0"){
		date.setDate(date.getDate() -6);
	}else {
		date.setDate(date.getDate() - date.getDay() + 1);
	}
	var myDate=date.getDate();
	var myMonth=date.getMonth() + 1;
	if(date.getDate()<10){
		myDate= '0'+ myDate;
	}
	if(date.getMonth() + 1<10){
		myMonth='0'+myMonth;
	}
	weekList.push(date.getFullYear() + "-" + myMonth+ "-" + myDate);
	// 获取周二以后日期
	for(var i=0;i<6;i++) {
		date.setDate(date.getDate() + 1);
		myDate=date.getDate();
		myMonth=date.getMonth() + 1;
		if(date.getDate()<10){
			myDate= '0'+ myDate;
		}
		if(date.getMonth() + 1<10){
			myMonth='0'+myMonth;
		}
		weekList.push(date.getFullYear() + "-" + myMonth+ "-" +myDate);
	}
	// console.log(weekList);
	return weekList
}

const getSystem = (data) =>{
	const systemInfo = uni.getSystemInfoSync();
	let platform = systemInfo.platform
	let system = '';
	if (platform === 'android') {
		system = 'android'
	} else if (platform === 'ios') {
		system = 'ios'
	}else if (platform === 'harmony') {
		system = 'harmony'
	} else {
		system = platform
	}
	
	return system
}

/**
 * 设置手机通知权限
 */
// 设置手机通知权限
const setPermissions = () =>{
	// #ifdef APP-PLUS  
	if (plus.os.name == 'Android') { // 判断是Android
		var main = plus.android.runtimeMainActivity();
		var pkName = main.getPackageName();
		var uid = main.getApplicationInfo().plusGetAttribute("uid");
		var NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");
		//android.support.v4升级为androidx
		if (NotificationManagerCompat == null) {
			NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
		}
		var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
		// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置  
		if (!areNotificationsEnabled) {
			uni.showModal({
				title: '通知权限开启提醒',
				content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
				showCancel: false,
				confirmText: '去设置',
				success: function(res) {
					if (res.confirm) {
						var Intent = plus.android.importClass('android.content.Intent');
						var Build = plus.android.importClass("android.os.Build");
						//android 8.0引导  
						if (Build.VERSION.SDK_INT >= 26) {
							var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
							intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
						} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
							var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
							intent.putExtra("app_package", pkName);
							intent.putExtra("app_uid", uid);
						} else { //(<21)其他--跳转到该应用管理的详情页  
							intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
							intent.setData(uri);
						}
						// 跳转到该应用的系统通知设置页  
						main.startActivity(intent);
					}
				}
			});
		}
	} else if (plus.os.name == 'iOS') { // 判断是ISO
		// var isOn = undefined;
		// var types = 0;
		// var app = plus.ios.invoke('UIApplication', 'sharedApplication');
		// var settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
		// if (settings) {
		// 	types = settings.plusGetAttribute('types');
		// 	plus.ios.deleteObject(settings);
		// } else {
		// 	types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
		// }
		// plus.ios.deleteObject(app);
		// isOn = (0 != types);
		// if (isOn == false) {
		// 	uni.showModal({
		// 		title: '通知权限开启提醒',
		// 		content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
		// 		showCancel: false,
		// 		confirmText: '去设置',
		// 		success: function(res) {
		// 			if (res.confirm) {
		// 				var app = plus.ios.invoke('UIApplication', 'sharedApplication');
		// 				var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
		// 				plus.ios.invoke(app, 'openURL:', setting);
		// 				plus.ios.deleteObject(setting);
		// 				plus.ios.deleteObject(app);
		// 			}
		// 		}
		// 	});
		// }
	}
	// #endif  
}

//处理时间为16进制指令，同步数据指令
const getTimeOrder = (date) =>{
	let _date = new Date(date)
	let year = '18'
	let month =uni.$_padHexString((_date.getMonth() + 1).toString(16),2)
	let day =uni.$_padHexString(_date.getDate().toString(16),2)
	let timeOrder = year+month+day
	// 将毫秒数转换为16进制字符串
	return timeOrder;	
}

const addAccess = (that) => {
	uni.$_get({
		url: "addAccess",
		that: that,
		needlogin: true,
		success: (res) => {
			
		},
		fail: (err) => {
			
		},
	});
}

export default {
	// 调用方式：uni.$_{name}(param)
	// 将[host1] [host2] 等替换成相应的 host 地址
	ab2hex,
	hex2int,
	getCrc_16_ibm,
	connectBluetooth,
	hexStringToArrayBuffer,
	startNotice,
	parse_blue_response,
	parseStrtoArr,
	changeHost,
	padHexString,
	getWeekDataList,
	getSystem,
	setPermissions,
	getTimeOrder,
	addAccess,
	// 同步获取storage信息 (同步/异步) 参数见 mystorage.getStorage
	getStorage: mystorage.getStorage,
	// 同步设置storage信息 (同步/异步) 参数见 mystorage.setStorage
	setStorage: mystorage.setStorage,
	// 同步清除storage信息
	removeStorage: mystorage.removeStorage,
	// 同步清除全部storage信息
	clearStorage: mystorage.clearStorage,
	// 请求封装（无loading 无toast）
	request,
	// 获取地址栏信息
	getParmas,
	// 路由
	navFn,
	// 获取微信登录凭证
	getWxLogin,
	// 修改页面标题
	changeTitle,
	// openid+code 登录
	loginWxMpPhone,
	// 获取当前年月日
	getNowDate,
	// 获取url参数
	getQueryString,
	// 定时器封装
	timeOut,
	//公共对话框
	publicModal,
	//消息订阅模板
	getSubscribe,
	getSubscribeList,
	getIsSubscribe,
	getUserSetting,
	//获取用户当前设置
	//消息订阅
	newsSubscription,
	//位置信息
	locationFn,
	//微信隐藏头部
	hidePageNavInWechatBrowser,
	//是否在微信
	isWeixin,
	//加密
	encrypt,
	momentTime,
	

}